package me.kagami.myjvm.jvm;


import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.*;

import java.util.Iterator;

public class MyJvm {


    public static MethodNode findMainMethod(ClassNode clazz) {
        return findPublicStaticMethod(clazz, "main");
    }

    public static MethodNode findPublicStaticMethod(ClassNode clazz, String methodName) {
        Iterator<?> it = clazz.methods.iterator();
        while (it.hasNext()) {
            MethodNode method = (MethodNode) it.next();
            if (method.name.equals(methodName) && hasModifier(method, Opcodes.ACC_PUBLIC) && hasModifier(method, Opcodes.ACC_STATIC)) {
                return method;
            }
        }
        return null;
    }

    public static boolean hasModifier(MethodNode method, int modifier) {
        return (method.access & modifier) != 0;
    }

    public static void run(ClassNode classNode, MethodNode methodNode, Object... args) {
        Frame frame = new Frame(methodNode.maxStack, methodNode.maxLocals,  methodNode.instructions, args);
        InstructionService.executeFrame(frame);

        System.out.println(frame.getReturnObj());
    }


}
